<template>
	<view class="page">
		<uni-forms ref="myForm" :modelValue="formData" :rules='rules' labelWidth="3em" class="my-form" type="line">
			<uni-forms-item label="账号" name="acc" class="form-item">
				<input name='acc' v-model="formData.acc" class="inp" type="text" placeholder="请输入账号" />
			</uni-forms-item>
			<uni-forms-item label="密码" name="pwd" class="form-item">
				<input name='pwd' v-model="formData.pwd" class="inp" type="safe-password" placeholder="请输入密码"
					password />
			</uni-forms-item>
			<view class="form-opts">
				<button @click="formSubmit" type="primary">进入</button>
			</view>
		</uni-forms>
	</view>
</template>

<script setup>
	import {
		onMounted,
		reactive,
		ref
	} from 'vue';
	import {
		loginOrRegister
	} from '@/api/user.js'

	const myForm = ref()
	const formData = reactive({
		acc: '',
		pwd: ''
	})
	const rules = {
		acc: {
			rules: [{
				required: true,
				errorMessage: '账号不能为空'
			}]
		},
		pwd: {
			rules: [{
				required: true,
				errorMessage: '密码不能为空'
			}]
		}
	}
	const formSubmit = () => {
		if (!myForm.value) {
			return
		}

		uni.showLoading({
			title: "请稍等"
		})

		myForm.value.validate().then(async (formValue) => {
			// console.log('success', formValue);
			for (const key in formValue) {
				const item = formValue[key]
				if (!item.trim()) {
					uni.showToast({
						title: "请填写完整!",
						icon: "none"
					})
					return
				}
			}
			// console.log('formValue', formValue);

			uni.setStorageSync('acc', formValue.acc)
			uni.setStorageSync('pwd', formValue.pwd)

			const user = await loginOrRegister(formValue.acc, formValue.pwd)
			if (user) {
				uni.showToast({
					title: '登录成功',
					success: () => {
						uni.setStorageSync('user', user)
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/home/home'
							})
						}, 3000);
					}
				})
			} else {
				uni.showToast({
					title: '登录失败',
					icon: 'fail'
				})
			}
		}).catch(() => {
			uni.hideLoading()
		})
	}

	onMounted(() => {
		formData.acc = uni.getStorageSync('acc') || ''
		formData.pwd = uni.getStorageSync('pwd') || ''
	})
</script>

<style lang="scss" scoped>
	page {
		background-color: #f8f8f8;
	}

	.page {
		padding: 10rpx;

		.my-form {
			margin: 160rpx auto 0;
			display: block;
			width: 520rpx;

			.form-item {
				display: flex;
				align-items: center;

				.inp {
					border: 1px solid #666;
					border-radius: 10rpx;
					height: 64rpx;
					padding: 0 12rpx;
				}
			}

			.form-opts {
				margin-top: 32rpx;
				display: flex;
				align-items: center;
			}
		}
	}
</style>